package com.javachmapi.springbootjsoup.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.javachmapi.springbootjsoup.constants.Constants;
import com.javachmapi.springbootjsoup.entity.Doctor;
import com.javachmapi.springbootjsoup.log.PeptileTaskLog;
import com.javachmapi.springbootjsoup.service.DoctorService;
import com.javachmapi.springbootjsoup.util.ResponseData;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * (Doctor)表控制层
 * @author 宋利军
 */
@Slf4j
@RestController
@RequestMapping("/doctor")
@Api(value = "DoctorController", tags = "采集京东互联网医生", description = "采集、医生")
public class DoctorController {
    /**
     * 服务对象
     */
    @Resource
    private DoctorService doctorService;

    /**
     * 采集医生数据
     */
    @GetMapping("/peptileInfo")
    @ApiOperation(value = "采集医生数据",notes = "采集京东医生数据存储到数据库")
    public ResponseData PeptileInfo(){
        try {
            Document doc =Jsoup.connect("https://api.healthjd.com/client") //url
                    .header("referer","https://m.healthjd.com/s/doctorList/2")
                    .data("body", "{\"pageIndex\":1,\"pageSize\":20,\"keyWords\":{\"departmentId\":69,\"searchEntryId\":4},\"fromDetail\":true}") //请求参数
                    .data("functionId", "NHPFCorePatientIndex/SearchDoctorList") //请求参数
                    .ignoreContentType(true) //忽略请求体类型
                    .timeout(60000)  //超时时间
                    .post();

            JSONObject object = JSONObject.parseObject(doc.text());  //把结果转为Json对象
            //总数
            int totalCount = object.getJSONObject("data").getIntValue("totalCount");
            //每页数量
            int pageSize = object.getJSONObject("data").getIntValue("pageSize");
            //下面模拟遍历翻页
            for (int pageIndex = 1; pageIndex < totalCount / pageSize + 1; pageIndex++) { //data遍历页数
                //第三步、首先爬取某个城市周边游的产品数量
                Document res = Jsoup.connect("https://api.healthjd.com/client") //url
                        .header("referer","https://m.healthjd.com/s/doctorList/2")
                        .data("body", "{\"pageIndex\":"+pageIndex+",\"pageSize\":20,\"keyWords\":{\"departmentId\":69,\"searchEntryId\":4},\"fromDetail\":true}") //请求参数
                        .data("functionId", "NHPFCorePatientIndex/SearchDoctorList") //请求参数
                        .ignoreContentType(true) //忽略请求体类型
                        .timeout(60000)
                        .post();
                JSONObject currentObject = JSONObject.parseObject(res.text());
                if (!currentObject.getString("msg").equals("OK")) {
                    ResponseData.failure("获取数据失败!");
                }
                //获取data.list.doctorInfoDTOList
                JSONArray doctorInfoDTOList = currentObject.getJSONObject( "data" ).getJSONArray( "doctorInfoDTOList" );
                //将json数组转为实体对象列表
                List<Doctor> list = JSONObject.parseArray(doctorInfoDTOList.toJSONString(),Doctor.class);
                try {
                    for (Doctor doctor:list) {
                        doctorService.insert(doctor);
                    }
                } catch (Exception e) {
                    PeptileTaskLog.pullProductLog("京东互联网医生","采集失败，原因:"+e.getMessage(),0, Constants.FAILURE.getName());
                    return ResponseData.failure("采集失败:"+e.getMessage(),e);
                }
            }
            PeptileTaskLog.pullProductLog("京东互联网医生","采集日志:一共采集了京东互联网医生人数:"+totalCount+"位！",totalCount, Constants.SUCCESS.getName());
            return ResponseData.success("采集完成！");
        } catch (IOException e) {
            PeptileTaskLog.pullProductLog("京东互联网医生","采集失败，原因:"+e.getMessage(),0, Constants.FAILURE.getName());
            return ResponseData.failure("采集失败，原因:"+e.getMessage());
        }
    }
}